package com.knowswift.account.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowswift.account.mapper.ModulePermissionMapper;
import com.knowswift.common.bean.project.po.ModulePermission;
import com.knowswift.common.bean.project.po.Project;
import com.knowswift.common.bean.project.vo.ModulePermissionVO;
import com.knowswift.common.bean.project.vo.ProjectLimit;
import com.knowswift.common.utils.WrappedBeanCopier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ModulePermissionService extends ServiceImpl<ModulePermissionMapper, ModulePermission> {

    public void concatData(List<ModulePermissionVO> list) {
        List<ProjectLimit> list1;
        List<Project> projectList;
        List<ProjectLimit> projectLimits;
        for (ModulePermissionVO permissionVO : list) {
            projectList = WrappedBeanCopier.JSONArrayToList(permissionVO.getProjectList(), Project.class);
            list1 = new ArrayList<>();
            projectLimits = WrappedBeanCopier.JSONArrayToList(permissionVO.getProjects(), ProjectLimit.class);
            for (Project project : projectList) {
                boolean flag = projectLimits.stream().noneMatch(projectLimit -> projectLimit.getProjectName().equals(project.getProjectName()));
                if (flag) {
                    ProjectLimit limit = WrappedBeanCopier.copyProperties(project, ProjectLimit.class);
                    limit.setLimit(false);
                    list1.add(limit);
                }
            }
            if (list1.isEmpty()) {
                continue;
            }
            projectLimits.addAll(list1);
            projectLimits = projectLimits.stream().sorted(Comparator.comparing(ProjectLimit::getProjectOrder)).collect(Collectors.toList());
            permissionVO.setProjects(projectLimits);
        }
    }
}